package com.zcoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcoj.core.model.PageData;
import com.zcoj.core.model.PageWrap;
import com.zcoj.mapper.UserRoleMapper;
import com.zcoj.pojo.Dto.UserRole;
import com.zcoj.service.UserRoleService;
import com.zcoj.util.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Service实现
 * @author 剩xia的盛夏
 * @date 2023/02/24 16:16
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Integer create(UserRole userRole) {
        userRoleMapper.insert(userRole);
        return userRole.getId();
    }

    @Override
    public void deleteById(Integer id) {
        userRoleMapper.deleteById(id);
    }

    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) return;
        userRoleMapper.deleteBatchIds(ids);
    }

    @Override
    public void updateById(UserRole userRole) {
        userRoleMapper.updateById(userRole);
    }

    @Override
    public void updateByIdInBatch(List<UserRole> userRoles) {
        if (CollectionUtils.isEmpty(userRoles)) return;
        for (UserRole userRole: userRoles) {
            this.updateById(userRole);
        }
    }

    @Override
    public UserRole findById(Integer id) {
        return userRoleMapper.selectById(id);
    }

    @Override
    public UserRole findOne(UserRole userRole) {
        Wrapper<UserRole> wrapper = new QueryWrapper<>(userRole);
        return userRoleMapper.selectOne(wrapper);
    }

    @Override
    public List<UserRole> findList(UserRole userRole) {
        Wrapper<UserRole> wrapper = new QueryWrapper<>(userRole);
        return userRoleMapper.selectList(wrapper);
    }
  
    @Override
    public PageData<UserRole> findPage(PageWrap<UserRole> pageWrap) {
        IPage<UserRole> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>(WrapperUtil.blankToNull(pageWrap.getModel()));
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase("DESC")) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(userRoleMapper.selectPage(page, queryWrapper));
    }

    @Override
    public long count(UserRole userRole) {
        Wrapper<UserRole> wrapper = new QueryWrapper<>(userRole);
        return userRoleMapper.selectCount(wrapper);
    }
}
